<?php

namespace app\api\server\order;

use app\api\model\coupon\CouponApiModel;
use app\api\model\order\OrderEntityApiModel;
use app\api\model\order\OrderEntityDetailApiModel;
use app\api\model\order\OrderMusicDetailApiModel;
use app\api\model\user\UserCouponApiModel;
use app\api\model\user\UserGoodsApiModel;
use app\api\model\vip\VipApiModel;
use app\api\ServerBase;
use app\api\validate\order\OrderMusicVal;
use app\logic\model\user\UserEntityCartLogicModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\EntitySingle;
use app\logic\single\OrderEntitySingle;
use app\logic\single\pay\AliPaySingle;
use app\logic\single\pay\WxPaySingle;
use Snow\Snow;
use think\facade\Db;
use think\facade\Queue;
use think\Request;

class OrderEntityServer extends ServerBase
{
    protected $model;
    protected $request;
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    private $user_id;
    /**
     * @var UserCouponApiModel
     */
    private $userCouponModel;
    /**
     * @var CouponApiModel
     */
    private $couponModel;
    /**
     * @var OrderMusicDetailApiModel
     */
    private $detailModel;
    /**
     * @var UserEntityCartLogicModel
     */
    private $userCartModel;
    /**
     * @var UserGoodsApiModel
     */
    private $userGoodsModel;
    /**
     * @var OrderMusicVal
     */
    private $validate;
    /**
     * @var VipApiModel
     */
    private $vipModel;
    /**
     * @var mixed
     */
    private $user_coupon_id;

    function __construct( Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model = new OrderEntityApiModel();
        $this->detailModel = new OrderEntityDetailApiModel();
        $this->validate = new OrderMusicVal();
        $this->userCouponModel = new UserCouponApiModel();
        $this->couponModel = new CouponApiModel();
        $this->user_id = $this->request->user_id;
        $this->userCartModel = new UserEntityCartLogicModel();
        $this->vipModel = new VipApiModel();
    }
    function getMyList(){
        [$page,$limit] = $this->getPage($this->param);
        $this->param['user_id']=$this->user_id;
        [$list,$count] = $this->model->getApiList($this->param,[],'*',$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }
    function cancel(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        $res = OrderEntitySingle::getInstance()->cancle($id);
        if(is_string($res)){
            $this->ERROR=$res;
            return false;
        }else{
            return true;
        }
    }
    function getDetail()
    {
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        $order['detail'] = $this->detailModel->getByOrderId($order['id']);
        return $order;
    }
    function take(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',2);
            return false;
        }
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->ERROR='订单不存在';
            return false;
        }
        if($order['status']  != 30){
            $this->ERROR='订单不能收货';
            return false;
        }
        if($order->save([
            'status'=>40,
            'take_time'=>date('Y-m-d H:i:s'),
        ])){
            $this->getMessageCode('code_common.success',2);
            return true;
        }else{
            $this->getMessageCode('code_common.error',1);
            return false;
        }

    }

    function refund(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',2);
            return false;
        }
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->ERROR='订单不存在';
            return false;
        }
        if($order['status']  != 20){
            $this->ERROR='订单不能申请退款';
            return false;
        }if($order->save([
            'status'=>-20,
            'cancel_time'=>date('Y-m-d H:i:s'),
        ])){
            $this->getMessageCode('code_common.success',2);
            return true;
        }else{
            $this->getMessageCode('code_common.error',1);
            return false;
        }
    }

    function create(){
        $is_cart= false;
        if(check_request($this->param,'goods_id') || check_request($this->param,'type')){
            //商品详情购买
            if(!$this->validate->scene('create')->check($this->param)){
                $this->ERROR = $this->validate->getError();
                return false;
            }
            $list[] =[
                'goods_id'=>$this->param['goods_id'],
                'type'=>$this->param['type']
            ];
        }
        else{
            //购物车购买
            $is_cart=true;
            $list = $this->userCartModel->where('user_id',$this->user_id)
                ->where('is_select',1)
                ->select()->toArray();
        }
        //判断对应的商品是否存在
        $list = EntitySingle::getInstance()->getGoodsList($list);
        if(empty($list)){
            $this->ERROR = '商品不存在';
            return false;
        }
        $order=[
            'buyer_id'=>$this->user_id,
        ];
        $order_detail=[];
        $order_price = 0;//订单原金额
        //验证商品
        foreach ($list as $key=>$val){
            if(!isset($val['goods']['id'])){
                $this->ERROR = '商品不存在';
                return false;
            }
            $order_price+=$val['goods']['price'];
            $order_detail[]=[
                'type'=>$val['type'],
                'goods_id'=>$val['goods_id'],
                'goods_price'=>$val['goods']['price'],
            ];
        }
        $pay_price = $order_price;
        //优惠券
        $coupon_id = $this->param['coupon_id']??0;
        $vip_coupon = $this->param['vip_coupon']??-1;
        if(!empty($coupon_id) && $vip_coupon == 1){
            $this->ERROR = 'VIP优惠和优惠券不能同时使用';
            return false;
        }

        $coupon_price = $this->getCouponPrice($coupon_id,$order_price);
        if($coupon_price === false){
            return false;
        }
        $vip_price = $this->getVipPrice($vip_coupon,$order_price);
        if($vip_price === false){
            return false;
        }
        $all_coupon_price = $coupon_price + $vip_price;
        if($all_coupon_price > 0){
            //支付金额减去优惠券金额
            $pay_price -= $all_coupon_price;
            $order['coupon_id'] = $coupon_id;
            $order['coupon_price'] = $coupon_price;
            $order['vip_price'] = $vip_price;
            $order_detail_count = count($order_detail);
            $single_coupon_price = round($all_coupon_price/$order_detail_count,2);
            foreach ($order_detail as &$val){
                $val['coupon_price']= $single_coupon_price;
            }
            unset($val);
        }

        $order['pay_price'] = $pay_price;
        $order['order_no'] = Snow::createOnlyId();
        $order['order_price'] = $order_price;
        Db::startTrans();
        try {
            $this->model->save($order);
            $order_id = $this->model->id;
            foreach ($order_detail as &$val){
                $val['order_id'] = $order_id;
            }
            unset($val);
            $this->userCartModel
                ->where('user_id',$order['buyer_id'])
                ->where('is_select',1)
                ->delete();
            $this->detailModel->saveAll($order_detail);
            //修改优惠券使用状态
            if(!empty($coupon_id)){
                $this->userCouponModel->where('id',$this->user_coupon_id)
                    ->save([
                        'status'=>2,
                        'order_id'=>$order_id,
                    ]);
            }
            $this->getMessageCode('code_common.success',2);
            Queue::later(600,'app\logic\queue\order_entity\Cancel',['order_id'=>$order_id],'order_entity_cancel');
            Db::commit();
            return $order_id;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR = $exception->getMessage();
            return false;
        }
    }

    function pay(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($order['status'] != 10){
            $this->ERROR = '该订单不能支付';
            return false;
        }

        $user = UserLogicModel::getInfoById($order['buyer_id']);
        $order['openid'] = $user['openid'];
        $terminal = $this->param['terminal']??'h5';
        $data=[];

        $details = $this->detailModel->getByOrderId($order['id']);
        $goodsList = EntitySingle::getInstance()->getGoodsList($details);
        $title = '';
        $i = 0;
        foreach ($goodsList as $val){
            if($i ==0){
                $title.=$val['goods']['title'];
            }else{
                $title.=','.$val['goods']['title'];
            }
            $i++;
        }
        //微信支付
        $res = WxPaySingle::getInstance()->pay($order,$terminal,'vip',$title);
        $data['wx_'.$terminal] = $res;
        //支付宝支付
        $res= AliPaySingle::getInstance()->pay($order,$terminal,'entity',$title,$this->param['ali_quit_url']??'',$this->param['ali_return_url']??'');
        $data['ali_'.$terminal] = $res;

        return $data;
    }
    function payByScore(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($order['status'] != 10){
            $this->ERROR = '该订单不能支付';
            return false;
        }
        if($this->request->user['score'] < $order['pay_price']){
            $this->ERROR = '积分不足';
            return false;
        }
        $res = OrderEntitySingle::getInstance()->complete($id,30);
        if($res[0] == -1){
            $this->ERROR = $res[1];
            return false;
        }
        return true;
    }

    private function getVipPrice($vip_coupon, $order_price)
    {
        $vip_id = $this->request->user['vip_id'];
        if($vip_coupon == 1){
            if($vip_id == -1){
                $this->ERROR = '不是vip用户,不能使用vip折扣';
                return false;
            }
            $vip = $this->vipModel->getFindById($vip_id);
            if(empty($vip)){
                $this->ERROR = 'vip不存在';
                return false;
            }
            return round($order_price * $vip['discount'] / 100 , 2);
        }else{
            return 0;
        }

    }

    private function getCouponPrice($coupon_id, $order_price)
    {
        $coupon['price']=0;
        if(!empty($coupon_id)){
            $user_coupon = $this->userCouponModel->getFindById($coupon_id,$this->user_id);
            if(empty($user_coupon)){
                $this->ERROR = '未找到优惠券';
                return false;
            }
            if($user_coupon['status'] == -1 || date('Y-m-d H:i:s') > $user_coupon['expire_time']){
                $this->ERROR = '优惠券已过期';
                return false;
            }
            if($user_coupon['status'] == 2){
                $this->ERROR = '优惠券已使用';
                return false;
            }
            //查询优惠券是否过期
            $coupon = $this->couponModel->getFindById($user_coupon['coupon_id']);
            if(empty($coupon)){
                $this->ERROR = '未找到优惠券';
                return false;
            }
            //使用条件
            if($order_price < $coupon['enough_price']){
                $this->ERROR = '未达到该优惠券使用金额';
                return false;
            }
            $this->user_coupon_id = $user_coupon['id'];
        }
        return $coupon['price'];
    }

}